package ar.edu.utn.frsf.tpae.a2013.g02.persistence.dao.impl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import ar.edu.utn.frsf.tpae.a2013.g02.persistence.dao.CentroCostoDao;
import ar.edu.utn.frsf.tpae.a2013.g02.persistence.model.CentroCosto;

/**
 * DAO de CentroCosto basado en Hibernate.
 * 
 * @author TPAE
 */
@Component
public class CentroCostoHibernetDao implements CentroCostoDao {

	private SessionFactory sessionFactory;

	
	// Setter utilizado por Spring.
	  @Autowired(required = true)
	  public void setSessionFactory(SessionFactory factory) {
	    this.sessionFactory = factory;
	  }

	  private Session getCurrentSession() {
	    return sessionFactory.getCurrentSession();
	  }
	  
	@Override
	public CentroCosto persistir(CentroCosto centroCosto) {
		if(centroCosto.getId() == null){
			getCurrentSession().save(centroCosto);
		} else {
			getCurrentSession().update(centroCosto);
		}
		return centroCosto;
	}

	@Override
	public void eliminar(CentroCosto centroCosto) {
		getCurrentSession().delete(centroCosto);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<CentroCosto> listar() {
		Query query = getCurrentSession().createQuery("from " + CentroCosto.class.getName());
		return query.list();
	}

	@Override
	public CentroCosto buscarPorId(Integer id) {
		return (CentroCosto) getCurrentSession().get(CentroCosto.class, id);
	}

}